<?php

namespace App\Http\Controllers\H5;

use App\Models\Item;
use App\Models\Shop;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class ShopController extends BaseController
{
    public function index()
    {
        $shops = [];
        Shop::whereHas('items', null, '>', 2)->opening()->limit(10)
            ->get()->map(function ($shop) use (&$shops){
            $shop->logo = image_url($shop->logo);
            $shop->items = [];
            $shops[$shop->shop_id] = $shop->toArray();
        });

        $prefix = DB::getTablePrefix();
        $query = DB::table(DB::raw($prefix."item as i"))
            ->where(DB::raw("(select count(*) from {$prefix}item where shop_id=i.shop_id and itemid<i.itemid)"),'<', 3);

        //echo $query->toSql();exit();
        $query->whereIn('shop_id', array_keys($shops))->orderByDesc('itemid')->get()->map(function ($item) use (&$shops){
            $item->thumb = image_url($item->thumb);
            $item->image = image_url($item->image);
            $shops[$item->shop_id]['items'][] = get_object_vars($item);
        });

        return $this->view('h5.shop.index', ['shops'=>$shops]);
    }

    public function viewShop($shop_id)
    {
        $shop = Shop::find($shop_id);
        if ($shop) {
            $shop->incrementViews();
            $shop->itemCount = $shop->items()->onSale()->count();
            $content = $shop->content;

            $catlogs = $shop->items()->with('catlog')->groupBy('catid')
                ->get()->map(function ($item){
                    if ($item->catlog)
                    {
                        return $item->catlog;
                    }
                });

            return $this->view('h5.shop.viewshop', compact('shop', 'content', 'catlogs', 'shop_id'));
        } else {
            return ajaxError(404, 'shop not found');
        }
    }

    public function getItems(Request $request)
    {
        $shop_id = $request->input('shop_id', 0);
        $query = Item::onSale()->where('shop_id', $shop_id);

        $catid = $request->input('catid', 0);
        if ($catid)
        {
            $query = $query->where('catid', $catid);
        }
        $items = $query->get()->map(function ($item){
            $item->thumb = image_url($item->thumb);
            $item->image = image_url($item->image);
            return $item;
        });

        return ajaxReturn(['items'=>$items]);
    }
}
